<template>
  <el-dialog
    v-model="props.show"
    width="600px"
    :append-to-body="true"
    :destroy-on-close="true"
    :before-close="close"
  >
    <template #default>
      <el-form
        ref="formRef"
        :model="form"
        label-width="90px"
      >
        <el-form-item label="角色名称" prop="roleName">
          <el-input placeholder="请输入角色名称" v-model="form.roleName" />
        </el-form-item>

        <el-form-item label="权限字符" prop="rolePerm">
          <el-input placeholder="请输入权限字符" v-model="form.rolePerm" />
        </el-form-item>

        <el-form-item label="状态" prop="enabled">
          <el-radio-group v-model="form.enabled">
            <el-radio
              v-for="item in system_global_status"
              :key="item.v"
              :label="item.v"
            >
              {{ item.k }}
            </el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="菜单权限">
          <div class="item-menu">
            <el-checkbox
              @change="toggleTreeCollapse"
              v-model="permission.openAll"
            >
              展开/折叠
            </el-checkbox>
            <el-checkbox
              @change="toggleTreeChecked"
              v-model="permission.selectAll"
            >
              全选/全不选
            </el-checkbox>
            <el-checkbox v-model="permission.linkage">
              父子(联动/不联动)
            </el-checkbox>
            <el-tree
              ref="menuTreeRef"
              :data="permission.treeList"
              :props="permission.treeProps"
              :check-strictly="!permission.linkage"
              :default-expand-all="permission.openAll"
              show-checkbox
              node-key="id"
              class="tree"
            />
          </div>
        </el-form-item>

        <el-form-item label="备注" prop="descript">
          <el-input
            type="textarea"
            placeholder="请输入内容"
            v-model="form.descript"
            :maxlength="200"
            show-word-limit
          />
        </el-form-item>
      </el-form>
    </template>

    <template #footer>
      <span class="dialog-footer">
        <el-button @click="close">取消</el-button>
        <el-button type="primary" @click="onSubmit"> 确认 </el-button>
      </span>
    </template>
  </el-dialog>
</template>
<script setup>
import { ref, reactive, onBeforeMount, watch } from "vue";
import { menuPage, addRole, roleGet, updateRole } from "@/utils/api/system.ts";
const props = defineProps({
  type: Number,
  show: Boolean,
  id: String,
});
const emit = defineEmits(["update:show"]);

const form = reactive({
  id: "",
  roleName: "",
  rolePerm: "",
  enabled: 1,
  descript: "",
});
const permission = reactive({
  treeList: [],
  treeProps: {
    label: "name",
  },
  selectAll: false,
  linkage: false,
  openAll: false,
});

const menuTreeRef = ref(null);

/*watch(() => props.id, (newId) => {
  if (newId) {
    getRoleData();
  }
});*/
if (props.id) {
  getRoleData();
}
// 修改角色
async function getRoleData(){
  let roleData = await roleGet(props.id);
    let { id, roleName, rolePerm, enabled, descript } = roleData.data.role;
    form.id = id;
    form.roleName = roleName; //角色名称
    form.rolePerm = rolePerm; //角色权限编码
    form.enabled = enabled; //下拉列表的value，值为1启用 0禁用
    form.descript = descript; //备注
    // setCheckedKeys：设置目前选中的节点(点击修改自动选中），使用此方法必须设置node-key属性
    menuTreeRef.value.setCheckedKeys(roleData.data.permissions);
}
// 生命周期
onBeforeMount(async () => {
  // 混入（获取字典）
  //proxy.sendDicts(['system_global_status'])
  // 菜单树
  let treeData = await menuPage({ current: 1, size: 1000 });
  permission.treeList = normalizeMenu(treeData.data.records,'-1',[]);
});
//重构数据结构 扁平化数据==》树形结构
const normalizeMenu = function (treeData,id,list) {
  for (const item of treeData) {
    if(item.parentId === id){
      list.push(item);
    }
  }
  for (const item of list) {
    normalizeMenu(treeData,item.id,item.children)
  }
  sortMenuList(list)
  return list;
};
//把重新构造的数据进行排序
const sortMenuList = function (list) {
  list.sort((a, b) => a.sort - b.sort);
  list.forEach((item) => {
    if (Array.isArray(item.children) && item.children.length > 1) {
      sortMenuList(item.children);
    }
  });
};

//全选/全不选
const toggleTreeChecked = function (value) {
  value
    ? permission.treeList.forEach((item) => {
        menuTreeRef.value.setChecked(item, value, true);
      })
    // : menuTreeRef.value.setCheckedKeys(value ? resolveTreeListKeys() : []);
    :menuTreeRef.value.setCheckedKeys([]);
    // 方法二
      // let nodesMap = menuTreeRef.value.store.nodesMap;
      // Object.keys(nodesMap).forEach((key) => (nodesMap[key].checked = value));
};
/*const resolveTreeListKeys = function () {
  let list = permission.treeList;
  return list.map((item) => {
    return [item.id, ...(item.children ? resolveTreeListKeys(item.children):[])]
  }).flat()
}*/
//展开&折叠菜单
const toggleTreeCollapse = function (value) {
  let nodesMap = menuTreeRef.value.store.nodesMap;
  //让所有el-tree封装的map数据，的expanded值全部设置为true就展开了
  //nodeMap[key]是每个节点
  Object.keys(nodesMap).forEach((key) => (nodesMap[key].expanded = value));
};

// 关闭dialog（点击取消 或 x）
const close = () => {
  ElMessageBox.confirm("Are you sure?").then(() => {
    ElMessage({ type: "success", message: "操作成功" });
    emit("update:show", false);
  });
};
// 提交表单
const onSubmit = async (isEdit) => {
  const { roleName, rolePerm, enabled, descript } = form;
  const params = {
    roleName,
    rolePerm,
    enabled,
    descript,
    permissionIds: menuTreeRef.value.getCheckedKeys(),
  };
  if (props.type === 2) {
    await updateRole({id:form.id,...params})
  }else if(props.type === 1){
    await addRole(params);
  }
  emit("change");
  emit("update:show", false);
};
</script>
